package com.dao;

import com.helper.DBHelper;
import com.helper.Util;
import com.model.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ExamResultDao {
	
	private ExamResult toExamResult(Map<String, Object> data)
	{
		ExamResult er = new ExamResult();
		er.setId((Integer)data.get("id"));
		er.setEexamId((Integer)data.get("exam_id"));
		er.setUserId((Integer)data.get("user_id"));
		er.setTime((String)data.get("time"));
		er.setScore((String)data.get("score"));
		er.setObjRatet((String)data.get("obj_rate"));
		return er;
	}
	
	
	public List<ExamResult> getAll()
	{
		List<ExamResult> result = new ArrayList<>();
		String sql = "select * from `exam_result`";
		DBHelper db = new DBHelper();
		List<Map<String, Object>> data = db.query(sql, null);
		for(Map<String, Object> ele : data) {
			result.add(toExamResult(ele));
		}
		return result;
	}

	
	public ExamResult getById(int id)
	{
		ExamResult result = new ExamResult();
		String sql = "select * from `exam_result` where id=" + id;
		DBHelper db = new DBHelper();
		List<Map<String, Object>> data = db.query(sql, null);
		for(Map<String, Object> ele : data) {
			result = toExamResult(ele);
		}
		return result;
	}

	public boolean delete(int userId)
	{
		String sql = "DELETE FROM `exam_result` where user_id=" + userId ;
		DBHelper db = new DBHelper();
		return db.update(sql, null);
	}

	public boolean add(int userId, int examId)
	{
		ExamDao examDao = new ExamDao();
		Exam exam = examDao.getById(examId+"");
		float[] res = Util.scoreCalculate(userId, exam);

		float score = res[0];
		float rate = res[1];

		String time = Util.getDateString();

		String sql = "INSERT INTO `exam_result`(`exam_id`, `user_id`, `time`, `score`, `obj_rate`) VALUES (?,?,?,?,?);";
		List<Object> param = new ArrayList<>();
		param.add(examId);
		param.add(userId);
		param.add(time);
		param.add(score+"");
		param.add(rate+"");
		DBHelper db = new DBHelper();
		return db.update(sql, param);
	}


	public boolean alreadyDone(int userId, int examId) {
		String sql = "select * from `exam_result` where exam_id=" + examId + " and user_id=" + userId ;
		DBHelper db = new DBHelper();
		List<Map<String, Object>> data = db.query(sql, null);
		return data.size()>0;
	}

	public ExamResult getOne(int userId, int examId) {
		ExamResult result = null;
		String sql = "select * from `exam_result` where exam_id=" + examId + " and user_id=" + userId ;
		DBHelper db = new DBHelper();
		List<Map<String, Object>> data = db.query(sql, null);
		for(Map<String, Object> ele : data) {
			result = toExamResult(ele);
		}
		return result;
	}

	public boolean updateResult(int eid, int uid, float score, float rate) {
		String sql = "UPDATE `exam_result` SET `score` = ?, `obj_rate` = ? WHERE `exam_id` = ? and `user_id` = ?";
		List<Object> param = new ArrayList<>();
		param.add(score+"");
		param.add(rate+"");
		param.add(eid);
		param.add(uid);
		DBHelper db = new DBHelper();
		return db.update(sql, param);
	}
}
